package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.zzyl.constant.CacheConstant;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.ResourceDto;
import com.zzyl.entity.Resource;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.ResourceMapper;
import com.zzyl.service.ResourceService;
import com.zzyl.utils.EmptyUtil;
import com.zzyl.utils.NoProcessing;
import com.zzyl.utils.StringUtils;
import com.zzyl.vo.ResourceVo;
import com.zzyl.vo.TreeItemVo;
import com.zzyl.vo.TreeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ResourceServiceImpl implements ResourceService {
    @Autowired
    private ResourceMapper resourceMapper;
    @Override
    @Cacheable(value = CacheConstant.RESOURCE_LIST ,key ="#resourceDto.hashCode()")
    public List<ResourceVo> findResourceList(ResourceDto resourceDto) {
        List<Resource> resourceList = resourceMapper.resourceList(resourceDto);
        return BeanUtil.copyToList(resourceList, ResourceVo.class);
    }

    /**
     * 资源树形
     * @param resourceDto 查询条件
     * @return: TreeVo
     */
    @Override
    public TreeVo resourceTreeVo(ResourceDto resourceDto) {

        //构建查询条件
        ResourceDto dto = ResourceDto.builder().dataState(SuperConstant.DATA_STATE_0)
                .parentResourceNo(NoProcessing.processString(SuperConstant.ROOT_PARENT_ID))
                .resourceType(SuperConstant.MENU)
                .build();

        //查询所有资源数据
        List<Resource> resourceList = resourceMapper.resourceList(dto);
        if(EmptyUtil.isNullOrEmpty(resourceList)){
            throw new RuntimeException("资源信息未定义");
        }
        //没有根节点，构建根节点
        Resource rootResource = new Resource();
        rootResource.setResourceNo(SuperConstant.ROOT_PARENT_ID);
        rootResource.setResourceName("智慧养老院");

        //返回的树形集合
        List<TreeItemVo> itemVos = new ArrayList<>();

        //使用递归构建树形结构
        recursionTreeItem(itemVos,rootResource,resourceList);

        //数据返回
        return TreeVo.builder().items(itemVos).build();
    }

    /**
     * 使用递归构建树形结构
     * @param itemVos
     * @param rootResource
     * @param resourceList
     */
    private void recursionTreeItem(List<TreeItemVo> itemVos, Resource rootResource, List<Resource> resourceList) {
        //构建每个资源的属性
        TreeItemVo treeItemVo = TreeItemVo.builder()
                .id(rootResource.getResourceNo())
                .label(rootResource.getResourceName()).build();

        //获取当前资源下子资源
        List<Resource> childrenResourceList = resourceList.stream()
                .filter(n -> n.getParentResourceNo().equals(rootResource.getResourceNo()))
                .collect(Collectors.toList());
        //判断子资源是否为空
        if(!EmptyUtil.isNullOrEmpty(childrenResourceList)){

            List<TreeItemVo> listChildren = new ArrayList<>();
            //构建子资源
            childrenResourceList.forEach(resource -> {
                recursionTreeItem(listChildren,resource,resourceList);
            });
            treeItemVo.setChildren(listChildren);
        }

        itemVos.add(treeItemVo);
    }

    /**
     * 添加资源
     * @param resourceDto
     */
    @Override
    public void createResource(ResourceDto resourceDto) {
        //属性拷贝
        Resource resource = BeanUtil.toBean(resourceDto, Resource.class);
        //查询父资源
        Resource parenResource = resourceMapper.selectByResourceNo(resourceDto.getParentResourceNo());
        resource.setDataState(parenResource.getDataState());

        boolean isIgnore = true;
        //判断是否是按钮，如果是按钮，则不限制层级
        if(StringUtils.isNotEmpty(resourceDto.getResourceType())
                && resourceDto.getResourceType().equals(SuperConstant.BUTTON)){
            isIgnore=false;
        }
        //创建当前资源的编号
        String resourceNo = createResourceNo(resourceDto.getParentResourceNo(),isIgnore);
        resource.setResourceNo(resourceNo);

        resourceMapper.insert(resource);

    }

    /**
     * 创建资源的编号
     * @param parentResourceNo
     * @return
     */
    private String createResourceNo(String parentResourceNo,boolean isIgnore) {

        //判断资源编号是否大于三级
        //100 001 000 000 000
        //100 001 001 000 000
        //100 001 001 001 000
        //100 001 001 001 001 001
        if(isIgnore && NoProcessing.processString(parentResourceNo).length() / 3 >= 5){
            throw new BaseException(BasicEnum.RESOURCE_DEPTH_UPPER_LIMIT);
        }

        //根据父资源编号查询子资源
        ResourceDto dto = ResourceDto.builder().parentResourceNo(parentResourceNo).build();
        List<Resource> resources = resourceMapper.resourceList(dto);
        if(EmptyUtil.isNullOrEmpty(resources)){
            //无下属节点，创建新的节点编号  100 001 001 001 000--->100 001 001 001 001
            return NoProcessing.createNo(parentResourceNo,false);
        }else {
            //有下属节点，在已有的节点上追加
            //先获取已有节点的最大值--100001003000000
            Long maxNo = resources.stream().map(resource -> {
                return Long.valueOf(resource.getResourceNo());
            }).max(Comparator.comparing(i -> i)).get();

            return NoProcessing.createNo(String.valueOf(maxNo),true);
        }
    }


    @Override
    public void updateResource(ResourceDto resourceDto) {
        Resource resource = BeanUtil.toBean(resourceDto, Resource.class);
        resourceMapper.updateByPrimaryKeySelective(resource);

    }

    @Override
    public void enable(ResourceDto resourceDto) {
        // 查询父级资源
        Resource parentResource = resourceMapper.selectByResourceNo(resourceDto.getParentResourceNo());
        Resource parentResource2 = resourceMapper.selectByResourceNo(resourceDto.getResourceNo());
//        if (parentResource.getDataState().equals(SuperConstant.DATA_STATE_1)) {
        if (parentResource2.getDataState().equals(SuperConstant.DATA_STATE_1)) {
            // 如果父级资源状态是禁用的，且传入的资源状态是禁用，则抛出异常
//            if (resourceDto.getDataState().equals(SuperConstant.DATA_STATE_1)) {
//                throw new RuntimeException("父级资源状态是禁用的，无法修改");
//            }
            resourceDto.setDataState(SuperConstant.DATA_STATE_0);
            resourceMapper.updateByResourceNo(resourceDto);
            disableChildResources2(resourceDto.getResourceNo());
        }

        // 查询当前资源
        Resource resource = resourceMapper.selectByResourceNo(resourceDto.getResourceNo());
        if (resource.getDataState().equals(SuperConstant.DATA_STATE_0) && resourceDto.getDataState().equals(SuperConstant.DATA_STATE_1)) {
            // 如果父级资源状态是启用的，且传入的资源状态是禁用，则禁用当前资源及其所有子级资源
            // 禁用当前资源
            resourceDto.setDataState(SuperConstant.DATA_STATE_1);
            resourceMapper.updateByResourceNo(resourceDto);

            // 禁用所有子级资源
            disableChildResources(resourceDto.getResourceNo());
        }
    }

    private void disableChildResources(String parentResourceNo) {
        List<Resource> childResources = resourceMapper.selectChildResourcesByParentNo(parentResourceNo);
        for (Resource childResource : childResources) {
            ResourceDto childDto = new ResourceDto();
            childDto.setResourceNo(childResource.getResourceNo());
            childDto.setDataState(SuperConstant.DATA_STATE_1);
            resourceMapper.updateByResourceNo(childDto);
            disableChildResources(childResource.getResourceNo()); // 递归禁用子级资源的子级资源
        }
    }

    private void disableChildResources2(String parentResourceNo) {
        List<Resource> childResources = resourceMapper.selectChildResourcesByParentNo(parentResourceNo);
        for (Resource childResource : childResources) {
            ResourceDto childDto = new ResourceDto();
            childDto.setResourceNo(childResource.getResourceNo());
            childDto.setDataState(SuperConstant.DATA_STATE_0);
            resourceMapper.updateByResourceNo(childDto);
            disableChildResources2(childResource.getResourceNo()); // 递归启用子级资源的子级资源
        }
    }
    @Override
    public void deleteResource(String resourceNo) {
        // 查询当前资源
        Resource resource = resourceMapper.selectByResourceNo(resourceNo);
        if (resource == null) {
            throw new RuntimeException("资源不存在");
        }

        // 检查当前资源的状态
        if (resource.getDataState().equals(SuperConstant.DATA_STATE_0)) {
            throw new RuntimeException("当前资源状态为禁用，无法删除");
        }

        // 如果当前资源状态为禁用，则删除当前资源及其所有子级资源
        deleteChildResources(resourceNo);
        resourceMapper.deleteByResourceNo(resourceNo);
    }


    private void deleteChildResources(String parentResourceNo) {
        List<Resource> childResources = resourceMapper.selectChildResourcesByParentNo(parentResourceNo);
        for (Resource childResource : childResources) {
            deleteChildResources(childResource.getResourceNo()); // 递归删除子级资源的子级资源
            resourceMapper.deleteByResourceNo(childResource.getResourceNo()); // 删除子级资源
        }
    }
}
